package stack_queue.p2_queue.linkedqueue;

public class LinkedQueue {
    private static class Node {
        int val;
        Node prev;
        Node next;
        public Node(int val, Node prev, Node next) {
            this.val = val;
            this.prev = prev;
            this.next = next;
        }
    }

    private Node front;
    private Node rear;

    public LinkedQueue() {
        front = null;
        rear = null;
    }

    public void enqueue(int val) {
        Node newNode = new Node(val, null, null);
        if (isEmpty()) {
            front = newNode;
        } else {
            rear.next = newNode;
        }
        rear = newNode;
    }

    public int dequeue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        int val = front.val;
        front = front.next;
        return val;
    }

    public int peek() {
        return front.val;
    }


    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[OUT << ");
        for (Node cur = front; cur != null; cur = cur.next) {
            sb.append(String.format(cur.next == null ? "%d" : "%d << ", cur.val));
        }
        return sb.append(" << IN]").toString();
    }

    public boolean isEmpty() {
        return front == null;
    }
}
